package ntd.util.str;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lj.netty.bean.ProtocolDetail;
import ntd.util.UtilCatch;

import java.util.List;
import java.util.function.Function;

public class ToolTemplateStrTransform {

    /**
     * 雨量站 16 进制数据解析
     * @param hex
     */
    public static <T> T parseHexString(String hex, Class<T> clazz, List<ProtocolDetail> protocolDetails) {
        return UtilCatch.tryCatch(() -> JSONUtil.toBean(parseHexString(hex, protocolDetails), clazz));
    }

    public static JSONObject parseHexString(String hex, List<ProtocolDetail> protocolDetails) {
        return UtilCatch.tryCatch(() -> {
            JSONObject jsonObject = new JSONObject();
            for (ProtocolDetail protocolDetail : protocolDetails) {
                String val = subVal(hex, protocolDetail);
                Function<String, String> transFun = protocolDetail.getEnumStrTransform().getTransform();
                if (ObjectUtil.isNotNull(transFun)) {
                    val = transFun.apply(val);
                }
                jsonObject.putOnce(protocolDetail.getKey(), val);
            }
            return jsonObject;
        });
    }

    private static String subVal(String hex, ProtocolDetail protocolDetail) {
        int startIndex = ObjectUtil.defaultIfNull(protocolDetail.getStartIndex(), 0);
        int endIndex = ObjectUtil.defaultIfNull(protocolDetail.getEndIndex(), hex.length());
        return StrUtil.sub(hex, startIndex, endIndex);
    }
}
